package com.mtaite.study.mybatis.flux.handler;

import com.mtaite.study.mybatis.common.RestResult;
import com.mtaite.study.mybatis.entity.UserDO;
import com.mtaite.study.mybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromObject;

/**
 * @author liqin
 */
@Component
public class UserHandler {


    @Autowired
    private UserMapper customerMapper;

    public Mono<ServerResponse> list(ServerRequest request) {
        return ServerResponse.ok().body(Flux.fromStream(customerMapper.findAll().stream()), UserDO.class);
    }

    public Mono<ServerResponse> findById(ServerRequest request) {
        return Mono.justOrEmpty(customerMapper.findById(request.pathVariable("id")))
            .flatMap(user -> ServerResponse.ok().body(Mono.just(user), UserDO.class))
                // // 输出 404 Not Found
            .switchIfEmpty(ServerResponse.notFound().build());
    }

    public Mono<ServerResponse> add(ServerRequest request) {
        return ServerResponse.ok().body(
            request.bodyToMono(UserDO.class)
                    .flatMap(userModel -> Mono.just(RestResult.success(customerMapper.adduser(userModel)))),
                RestResult.class);
    }

    public Mono<ServerResponse> update(ServerRequest request) {
        return request.bodyToMono(UserDO.class)
            .flatMap(body -> Mono.justOrEmpty(customerMapper.findById(body.getId())).flatMap(foundUser -> {
                //foundUser.setAge(body.getAge());
                foundUser.setName(body.getName());
                return Mono.just(foundUser);
            }).flatMap(u -> ServerResponse.ok().body(fromObject(u))).switchIfEmpty(ServerResponse.notFound().build()));
    }

    public Mono<ServerResponse> deleteById(ServerRequest request) {
        return Mono.justOrEmpty(customerMapper.findById(request.pathVariable("id")))
            .switchIfEmpty(Mono.error(new RuntimeException(request.pathVariable("id") + "not found!"))) // 控制台异常：RuntimeException: 30
            .then(ServerResponse.ok()
                    .body(Mono.justOrEmpty(customerMapper.delById(request.pathVariable("id"))), Integer.class));
    }

    public Mono<ServerResponse> deleteId(ServerRequest request) {
        String id = request.pathVariable("id");
        return Mono.justOrEmpty(customerMapper.findById(id))
            .flatMap(user -> ServerResponse.ok().body(Mono.just(customerMapper.delById(id)), Integer.class))
            .switchIfEmpty(ServerResponse.notFound().build());
    }
}
